<template>
  <div v-if="selectWidget && selectWidget.options && selectWidget.options.options">
    <el-checkbox-group v-model="computedValue">
      <draggable
        v-model="selectWidget.options.options"
        v-bind="{ group: 'selectGroup', animation: 200, handle: '.drag-select' }"
        item-key="id"
        tag="div"
      >
        <div v-for="(item, index) in selectWidget.options.options" :key="index" class="select-item">
          <el-radio v-if="!multiple" v-model="computedValue" :label="item.id" @click.native.prevent="clickitem(item)"><span/></el-radio>
          <el-checkbox v-else :label="item.id" @change="checkboxChange"><span/></el-checkbox>
          <el-input
            v-model="item.id"
            :type="isNumberField?'number':'text'"
            placeholder="请输入"
            class="width180"
            size="small"
            @change="numberInputChange(item)" />
          <div class="select-item-drag">
            <i class="el-icon-rank drag-select" />
          </div>
          <div v-if="selectWidget.options.options.length > 0" class="select-item-drag">
            <i class="el-icon-delete" @click="deleteItem(index)"/>
          </div>
        </div>
      </draggable>
    </el-checkbox-group>
    <div class="tool-foot">
      <div class="button-text" @click="addItem">添加选项</div>
      <div class="button-text bl" @click="openDialog">批量编辑</div>
    </div>
    <el-dialog
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
      :append-to-body="true"
      class="small-common-dialog-size"
    >
      <Title title="批量编辑选项" style="margin-bottom: 10px;" />
      <div class="tip">提示：每行为一项，换行添加新项{{ isNumberField?'，请输入数值型选项':'' }}</div>
      <div>
        <el-input v-model="batchContent" placeholder="请输入内容" rows="6" type="textarea" resize="none" size="small" />
      </div>
      <div class="btn">
        <el-button type="primary" size="small" @click="toSubmit()">确定</el-button>
        <el-button type="info" size="small" class="cancel-btn-style" @click="handleClose">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import draggable from 'vuedraggable';
import Title from '@/components/Title';
import { isNumber } from '@/utils/tools';
import { isNumberType } from '@/utils/formMakeUtils.js';
export default {
  components: { draggable, Title },
  model: {
    prop: 'selectWidget',
    event: 'changeData'
  },
  props: {
    selectWidget: {
      type: Object,
      default: () => ({})
    },
    multiple: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogFormVisible: false,
      batchContent: ''
    };
  },
  computed: {
    computedValue: {
      get() {
        if (this.selectWidget.value === '') return undefined;
        return this.selectWidget.value;
      },
      set(val) {
        this.$set(this.selectWidget, 'value', val);
      }
    },
    isNumberField() { // 是否数值型字段
      if (this.selectWidget.type === 'input' && this.selectWidget.options.dataType === 'number') {
        return true;
      }
      return false;
    }
  },
  watch: {
    'selectWidget.options.options': {
      handler: function(newVal) {
        this.$emit('statusCheck');
        const value = this.selectWidget.value;
        if (value) {
          if (typeof value === 'string') {
            const hasVal = newVal.some(i => i.id === value);
            if (!hasVal) {
              this.selectWidget.value = '';
            }
          } else if (Array.isArray(value) && value.length) {
            const ids = newVal.map(i => i.id);
            this.selectWidget.value = this.selectWidget.value.filter(i => ids.includes(i));
          }
        }
      },
      deep: true
    }
  },
  methods: {
    clickitem(item) {
      if (item.id !== this.selectWidget.value) {
        this.selectWidget.value = item.id;
      } else {
        this.selectWidget.value = undefined;
      }
      this.$emit('changeValue');
      // this.$emit('changeData', this.selectWidget);
    },
    deleteItem(index) {
      this.selectWidget.options.options.splice(index, 1);
      // this.$emit('changeData', this.selectWidget);
    },
    addItem() {
      // let index = this.selectWidget.options.options.length + 1;
      // this.selectWidget.options.options.forEach(i => {
      //   if (i.id === `选项${index}`) {
      //     index++;
      //   }
      // });
      // const id = this.isNumberField ? '' : `选项${index}`;
      this.selectWidget.options.options.push({ id: '' });
      // this.$emit('changeData', this.selectWidget);
    },
    openDialog() {
      let batchContent = '';
      if (this.selectWidget.options && this.selectWidget.options.options) {
        this.selectWidget.options.options.forEach(i => {
          if (i.id) batchContent += `${i.id}\n`;
        });
      }
      this.batchContent = batchContent;
      this.dialogFormVisible = true;
    },
    handleClose() {
      this.dialogFormVisible = false;
      this.batchContent = '';
    },
    checkboxChange(e) {
      const value = this.selectWidget.value;
      if (Array.isArray(value) && value && value.length) {
        this.selectWidget.value = value.filter(i => i || i === 0);
      }
    },
    toSubmit() {
      const content = this.batchContent;
      if (!content) {
        this.handleClose();
        this.selectWidget.options.options = [];
        return;
      }
      const element = this.selectWidget;
      let minVal = -99999999999;
      let maxVal = 99999999999;
      if (element.options.numberRange) {
        minVal = element.options.numberRange[0] || element.options.numberRange[0] === 0 ? element.options.numberRange[0] : -99999999999;
        maxVal = element.options.numberRange[1] || element.options.numberRange[1] === 0 ? element.options.numberRange[1] : 99999999999;
      }

      const arr = content.split(/[\n]/);
      if (arr && arr.length) {
        const options = [];
        arr.forEach(i => {
          let id = i ? i.trim() : '';
          if (id && !this.isRepeat(options, id)) {
            if (!this.isNumberField || (this.isNumberField && isNumber(id) && Number(id) >= minVal && Number(id) <= maxVal)) {
              const precision = element.options.precision;
              if (this.isNumberField && isNumber(id) && (precision || precision === 0)) {
                id = Number(id).toFixed(precision);
              }
              options.push({ id });
            }
          }
        });
        this.selectWidget.options.options = options;
      }
      // this.$emit('changeData', this.selectWidget);
      this.handleClose();
    },
    isRepeat(options, name) {
      return options.some(i => i.id === name);
    },
    numberInputChange(item) {
      const element = this.selectWidget;
      if (isNumberType(element)) {
        let minVal = -99999999999;
        let maxVal = 99999999999;
        if (element.options.numberRange) {
          minVal = element.options.numberRange[0] || element.options.numberRange[0] === 0 ? element.options.numberRange[0] : -99999999999;
          maxVal = element.options.numberRange[1] || element.options.numberRange[1] === 0 ? element.options.numberRange[1] : 99999999999;
        }
        if (item.id || item.id === 0) {
          if (Number(item.id) < minVal) item.id = minVal;
          if (Number(item.id) > maxVal) item.id = maxVal;

          const precision = element.options.precision;
          if (precision || precision === 0) {
            item.id = Number(Number(item.id).toFixed(precision));
          }
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.select-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  .width180 {
    width: 170px;
  }
  .select-item-drag {
    margin-left: 5px;
    font-size: 14px;
  }
  .el-icon-delete {
    cursor: pointer;
  }
  .drag-select {
    font-size: 14px;
    color: #333;
    cursor: move;
    &:hover {
      color: #406eff;
    }
  }
  .el-radio {
    margin-right: 0;
    &::v-deep {
      .el-radio__inner {
        box-shadow: none !important;
      }
    }
  }
}
.tool-foot {
  // padding-left: 24px;
  display: flex;
  margin-bottom: 10px;
  .button-text {
    line-height: 1.2;
  }
}
.btn {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}
.tip{
  font-size: 12px;
  color: #999;
}
</style>
